#include "include/ppread.h"
#include <iostream>
#include <fstream>
#include <boost/regex.hpp>
using namespace std;

ppread::ppread(){
    strFileName = "";
}

ppread::ppread(string file){
    strFileName = file;
    buildDB();
}

ppread::~ppread(){
 
}

void ppread::buildDB(){
    ifstream fp(strFileName.c_str(), ios::in);
    char str[255];
    if(!fp.eof() && fp.is_open()){
        fp.getline(str, 255);
        str[strlen(str) -1] = '\0';
        nMovieID = atoi(str);
    }else{
        std::cout<<"File not open or is empty!"<<endl;
    }

    /*
    * These are the regex objects that will help us parse
    * the string from the file.
    */
    boost::regex re;
    boost::cmatch matches;

    try{
        re = "(\\d+),(\\d)+,.*";
    }catch(boost::regex_error& err){
        std::cout<<str<<" is not a valid Regular exrpression because \""\
        <<err.what()<<"\""<<endl;
        exit(-1);
    }

     while(!fp.eof()){
        fp.getline(str, 255);
        //std::cout<<str<<"++"<<endl;
     if(strlen(str) < 1)
        continue;
     if (boost::regex_match(str, matches, re)){
        string arNums[2];
        for (unsigned int i = 1; i < 3; i++){
            string match(matches[i].first, matches[i].second);
            //cout<<matches[i].first<<matches[i].second<<endl;
            arNums[i-1] = match;
            //cout<<match<<endl;
        }
        mpCustRating[atoi(arNums[0].c_str())] = (short)atoi(arNums[1].c_str());
      }else{
            std::cout<<"File not in required format. Please check the file "<<strFileName<<endl;
            std::cout<<str<<"--"<<endl;
      }

     }
}

short ppread::getMovieID(){
    return nMovieID;
}

short ppread::getRating(int CustID){
    if(mpCustRating.find(CustID) != mpCustRating.end())
        return mpCustRating[CustID];
    else
        return -1;
}

vector<int> ppread::getCustIDs(){
    vector<int> vecCustIDs;

    for(map<int, short>::iterator itrmpCustIDs=mpCustRating.begin();
        itrmpCustIDs != mpCustRating.end();
        itrmpCustIDs++){
            vecCustIDs.push_back((*itrmpCustIDs).first);
        }

    return vecCustIDs;

}
